package jp.co.piratealliance.pirateAllianceWeb.web.action.goods;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import jp.co.piratealliance.pirateAllianceWeb.common.base.BaseAction;
import jp.co.piratealliance.pirateAllianceWeb.common.util.NumberUtils;
import jp.co.piratealliance.pirateAllianceWeb.def.Constants;
import jp.co.piratealliance.pirateAllianceWeb.def.SystemConf;
import jp.co.piratealliance.pirateAllianceWeb.dto.com.UserInfoDto;
import jp.co.piratealliance.pirateAllianceWeb.dto.goods.GoodsInfoDto;
import jp.co.piratealliance.pirateAllianceWeb.dto.goods.ResourceTypeInfoDto;
import jp.co.piratealliance.pirateAllianceWeb.helper.CommonHelper;
import jp.co.piratealliance.pirateAllianceWeb.service.goods.GoodsService;


/**
 * copyright pirate alliance team 2014
 *
 * @author panxuejuan
 */

public class GetResourceListWebAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private GoodsService goodsService;
	
	private List<GoodsInfoDto> goodsList;
	
	private List<ResourceTypeInfoDto> resourceList;
	
	private GoodsInfoDto goodsInfoForResource;
	
	private Map<String, String> currencyUnitIdMap;
	
	private String goods_id;
	
	private int goods_type_id;
	
	private String user_id;
	
	private int currency_unit_id;
	
	private BigDecimal price;
	
	private String priceForResource;
	
	private String descriptionx;
	
	private int status;
	
	private int statusForResource;//使用状态
	
	private String area_id;
	
	private String language_id;
	
	private int start_row;
	
	private int end_row;
	
	private String goods_img;
	
	private String userId;
	
    private File file;

    private String fileContentType;

    private String fileFileName;
	
    private String fileImgPath;
    private String resourceType_descriptionx;
    private String initFlag;
    private String mapFlag;

	public String getMapFlag() {
		return mapFlag;
	}

	public void setMapFlag(String mapFlag) {
		this.mapFlag = mapFlag;
	}

	public String getInitFlag() {
		return initFlag;
	}

	public void setInitFlag(String initFlag) {
		this.initFlag = initFlag;
	}

	public String getResourceType_descriptionx() {
		return resourceType_descriptionx;
	}

	public void setResourceType_descriptionx(String resourceType_descriptionx) {
		this.resourceType_descriptionx = resourceType_descriptionx;
	}

	private String goodsIdForModify="";
	
	private String languageIdForModify="";
	
	private int resourceTypeId;

	public void prepare() {
		//初始化:货币下拉框
		currencyUnitIdMap=goodsService.getCurrencyUnitIdMap();
		doInit();
	}
	
	//进入新增资源信息初始化页面
	public String doInit() {
		UserInfoDto userDto=(UserInfoDto) ActionContext.getContext().getSession().get("user");
		if(userDto!=null){
			this.statusForResource=1;
		this.goodsList=goodsService.getResorceGoodsListByUserId(userDto.getUser_id());
		resourceList = goodsService.getResourceTypeListInfo();
		return SUCCESS;
		}
		return INPUT;
	}
	

	

	public void validateAddResourceInfo() {
		// TODO Auto-generated method stub、
		if(priceForResource != null && !NumberUtils.checkNumberValid(priceForResource)&&!priceForResource.equals("")){
		this.addFieldError("priceForResource",getText("validation0003", new String[]{getText("label_goodsPrice")}));
	}
		if(area_id.equals("")||area_id==null){
			this.addFieldError("area_id",getText("validation0001", new String[]{getText("label_goodsArea")}));
		}
		if(file==null&&goods_img==null){
			this.addFieldError("file",getText("validation0014"));
		}
		
		if(descriptionx.length()>350){
			this.addFieldError("descriptionx", getText("validation0012"));
		}
	}
	public void validateUpdateResourceInfo() {
		String goods_img= ServletActionContext.getRequest().getParameter("goods_img");
		this.goods_img=goods_img;
		this.initFlag="1";
		validateAddResourceInfo();
	}
	//资源信息保存
	public String addResourceInfo() throws IOException
	{
//		boolean isSuccess=true;
//		if(priceForResource != null && !NumberUtils.checkIntNumberValid(priceForResource)){
//			this.addFieldError("priceForResource",getText("validation0003", new String[]{getText("label_goodsPrice")}));
//			isSuccess=false;
//		}
//		if(isSuccess){
			//		this.saveFile(file,fileContentType, fileFileName,"jp" );
			//String fileFileName= ServletActionContext.getRequest().getParameter("fileFileName");
			String resourceTypeId= ServletActionContext.getRequest().getParameter("resourceTypeId");
			GoodsInfoDto goodsInfoForResource = new GoodsInfoDto();
			String goodsIdSeq = CommonHelper.getSequence(Constants.TB_GOODS);
			goodsInfoForResource.setGoods_id(goodsIdSeq);//商品Id
			goodsInfoForResource.setResource_type_id(Integer.parseInt(resourceTypeId));
			goodsInfoForResource.setGoods_type_id(1);//1：资源商品
			goodsInfoForResource.setArea_id(this.area_id);//所在区域
			goodsInfoForResource.setLanguage_id(this.language_id);//言语Id
			goodsInfoForResource.setPrice(new BigDecimal(priceForResource));//日租金
			goodsInfoForResource.setCurrency_unit_id(this.currency_unit_id);//货币Id
			goodsInfoForResource.setStatus(this.status);//使用状态
			
			UserInfoDto userDto=(UserInfoDto) ActionContext.getContext().getSession().get("user");
			goodsInfoForResource.setUser_id(userDto.getUser_id());//ユーザーID
			goodsInfoForResource.setPay_type_id(3);//支払い分類ID

			if(fileFileName!=null && !fileFileName.isEmpty()){
				//goodsInfoForResource.setGoods_img(fileFileName);//图片写真
				goodsInfoForResource.setGoods_img(Constants.RESOURCE_IMAGE_PATH+Constants.PATH_SEPEARTOR+goodsIdSeq+Constants.PATH_SEPEARTOR+language_id+Constants.PATH_SEPEARTOR+fileFileName);
				this.saveFile(file, fileContentType, fileFileName, language_id, goodsIdSeq);//保存图片文件
			}
			goodsInfoForResource.setDescriptionx(this.descriptionx);//说明
          
		
			goodsService.insertResourceInfo(goodsInfoForResource);//新增资源信息
//		}
		doInit();
		cleardata();
		return SUCCESS;
	}
	public String updateResourceInfoInit(){
		String goodsId= ServletActionContext.getRequest().getParameter("goodsid");
		this.goodsInfoForResource=goodsService.getGoodsListByGoodsId(goodsId).get(0);
		this.area_id=goodsInfoForResource.getArea_id();
		this.language_id=goodsInfoForResource.getLanguage_id();
		this.goods_id=goodsInfoForResource.getGoods_id();
		this.price=goodsInfoForResource.getPrice();
		this.priceForResource=String.valueOf(goodsInfoForResource.getPrice());
		this.status=goodsInfoForResource.getStatus();
		this.statusForResource=status;
		this.currency_unit_id=goodsInfoForResource.getCurrency_unit_id();
		this.descriptionx=goodsInfoForResource.getDescriptionx();
		this.goods_img=goodsInfoForResource.getGoods_img();
		this.resourceType_descriptionx=goodsInfoForResource.getResource_descriptionx();
		this.initFlag="1";
		goodsIdForModify="1";
		this.mapFlag="1";
	
		return SUCCESS;

	}
	
	
	
	public String updateResourceInfo() throws IOException
	{   
		String goods_id= ServletActionContext.getRequest().getParameter("goods_id");
		GoodsInfoDto goodsInfoForResource = new GoodsInfoDto();
		goodsInfoForResource.setGoods_id(goods_id);//商品Id
		goodsInfoForResource.setLanguage_id(this.language_id);//言语Id
		goodsInfoForResource.setGoods_type_id(1);//1：资源商品
		goodsInfoForResource.setArea_id(this.area_id);//所在区域
		goodsInfoForResource.setPrice(new BigDecimal(priceForResource));//日租金
		goodsInfoForResource.setCurrency_unit_id(this.currency_unit_id);//货币Id
        goodsInfoForResource.setStatus(this.status);//使用状态
		if(fileFileName!=null && !fileFileName.isEmpty()){
			//goodsInfoForResource.setGoods_img(fileFileName);//图片写真
			goodsInfoForResource.setGoods_img(Constants.RESOURCE_IMAGE_PATH+Constants.PATH_SEPEARTOR+goods_id+Constants.PATH_SEPEARTOR+language_id+Constants.PATH_SEPEARTOR+fileFileName);
			this.saveFile(file, fileContentType, fileFileName, language_id, goods_id);//保存图片文件
		}	
		goodsInfoForResource.setDescriptionx(this.descriptionx);//说明
		goodsService.updateResourceInfo(goodsInfoForResource);
	
		return SUCCESS;
	}
	
	private void cleardata(){
		this.goodsInfoForResource=null;
		this.area_id=null;
		this.language_id=null;
		this.goods_id=null;
		this.priceForResource=null;
		this.status=1;
		this.statusForResource=status;
		this.currency_unit_id=3;
		this.descriptionx=null;;
		this.goods_img=null;
	}
	//进入资源信息编辑画面
	public String modifyResourceInfoInit()
	{   
		cleardata();
	    this.initFlag="2";
		String resourceTypeIdSeq = ServletActionContext.getRequest().getParameter("resourceTypeId");
		resourceTypeId = Integer.valueOf(resourceTypeIdSeq);
		goodsIdForModify= String.valueOf(resourceTypeId);
		List<ResourceTypeInfoDto> resourceInfoList = goodsService.getResourceListInfo(resourceTypeId);
		for(ResourceTypeInfoDto resourceListInfo:resourceInfoList){
			//fileImgPath = "http://localhost:8080/pirateAllianceWeb/images/resourcePhotos/jp/"+resourceListInfo.getImg();
			resourceType_descriptionx = resourceListInfo.getDescriptionx();
		}
		doInit();
		return SUCCESS;
	}

//	private void saveFile(File file1,String file1ContentType, String file1Name, String path1Name) throws IOException{
//		// 以服务器的文件保存地址和原文件名建立上传文件输出流
//		 // String path=ServletActionContext.getServletContext().getRealPath("/images/resourcePhotos/"+path1Name);
//		  String  path = SystemConf.getImageRootDir() + Constants.PATH_SEPEARTOR + Constants.RESOURCE_IMAGE_PATH + Constants.PATH_SEPEARTOR;   
//		if(file1==null)
//	        {
//	            this.addFieldError("file1", "文件不能为空，请选择");
//	        }else
//	        {
//	        	
//	        	
//	            InputStream is=new FileInputStream(file1);
//
//	            OutputStream os=new FileOutputStream(new File(path,file1Name));
//
//	            byte[] buf=new byte[1024];
//
//	            int length=0;
//
//	            while((length=is.read(buf))>0)
//
//	            {
//	                os.write(buf, 0, length);
//	            }
//	            is.close();
//	            os.close();
//	        }  
//	}
//	
	
	private void saveFile(File file,String fileContentType, String fileName, String langName,String goodsId) throws IOException{
		
	       if(file==null)
	        {
	    	   return ;
	        }
			
			// 以服务器的文件保存地址和原文件名建立上传文件输出流
	       String  rootPath = SystemConf.getImageRootDir() + Constants.PATH_SEPEARTOR + Constants.RESOURCE_IMAGE_PATH + Constants.PATH_SEPEARTOR;
			File savePath = new File(rootPath+Constants.PATH_SEPEARTOR+ goodsId+Constants.PATH_SEPEARTOR+langName);
			if(!savePath.exists()){
				savePath.mkdirs();
			}
			
			String path = SystemConf.getImageRootDir()+Constants.PATH_SEPEARTOR + Constants.RESOURCE_IMAGE_PATH + Constants.PATH_SEPEARTOR+goodsId+Constants.PATH_SEPEARTOR+langName;
	        InputStream is=new FileInputStream(file);

	        OutputStream os=new FileOutputStream(new File(path,fileName));

	        byte[] buf=new byte[1024];

	        int length=0;

	        while((length=is.read(buf))>0)

	        {
	            os.write(buf, 0, length);
	        }
	        is.close();
	        os.close();        
		}
		
	/**
	 * @return the goodsService
	 */
	public GoodsService getGoodsService() {
		return goodsService;
	}

	/**
	 * @param goodsService the goodsService to set
	 */
	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	/**
	 * @return the goods_type_id
	 */
	public int getGoods_type_id() {
		return goods_type_id;
	}

	/**
	 * @param goods_type_id the goods_type_id to set
	 */
	public void setGoods_type_id(int goods_type_id) {
		this.goods_type_id = goods_type_id;
	}

	/**
	 * @return the area_id
	 */
	public String getArea_id() {
		return area_id;
	}

	/**
	 * @param area_id the area_id to set
	 */
	public void setArea_id(String area_id) {
		this.area_id = area_id;
	}

	/**
	 * @return the language_id
	 */
	public String getLanguage_id() {
		return language_id;
	}

	/**
	 * @param language_id the language_id to set
	 */
	public void setLanguage_id(String language_id) {
		this.language_id = language_id;
	}

	/**
	 * @return the start_row
	 */
	public int getStart_row() {
		return start_row;
	}

	/**
	 * @param start_row the start_row to set
	 */
	public void setStart_row(int start_row) {
		this.start_row = start_row;
	}

	/**
	 * @return the end_row
	 */
	public int getEnd_row() {
		return end_row;
	}

	/**
	 * @param end_row the end_row to set
	 */
	public void setEnd_row(int end_row) {
		this.end_row = end_row;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}
	
	public String getDescriptionx() {
		return descriptionx;
	}

	public void setDescriptionx(String descriptionx) {
		this.descriptionx = descriptionx;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public int getCurrency_unit_id() {
		return currency_unit_id;
	}

	public void setCurrency_unit_id(int currency_unit_id) {
		this.currency_unit_id = currency_unit_id;
	}

	public String getUser_id() {
		return user_id;
	}

	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}

	public List<GoodsInfoDto> getGoodsList() {
		return goodsList;
	}

	public void setGoodsList(List<GoodsInfoDto> goodsList) {
		this.goodsList = goodsList;
	}

	public Map<String, String> getCurrencyUnitIdMap() {
		return currencyUnitIdMap;
	}

	public void setCurrencyUnitIdMap(Map<String, String> currencyUnitIdMap) {
		this.currencyUnitIdMap = currencyUnitIdMap;
	}

	public String getGoods_id() {
		return goods_id;
	}

	public void setGoods_id(String goods_id) {
		this.goods_id = goods_id;
	}

	public GoodsInfoDto getGoodsInfoForResource() {
		return goodsInfoForResource;
	}

	public void setGoodsInfoForResource(GoodsInfoDto goodsInfoForResource) {
		this.goodsInfoForResource = goodsInfoForResource;
	}
	
	public String getGoods_img() {
		return goods_img;
	}

	public void setGoods_img(String goods_img) {
		this.goods_img = goods_img;
	}
	
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileImgPath() {
		return fileImgPath;
	}

	public void setFileImgPath(String fileImgPath) {
		this.fileImgPath = fileImgPath;
	}

	public String getGoodsIdForModify() {
		return goodsIdForModify;
	}

	public void setGoodsIdForModify(String goodsIdForModify) {
		this.goodsIdForModify = goodsIdForModify;
	}

	public int getStatusForResource() {
		return statusForResource;
	}

	public void setStatusForResource(int statusForResource) {
		this.statusForResource = statusForResource;
	}

	public String getPriceForResource() {
		return priceForResource;
	}

	public void setPriceForResource(String priceForResource) {
		this.priceForResource = priceForResource;
	}

	public String getLanguageIdForModify() {
		return languageIdForModify;
	}

	public void setLanguageIdForModify(String languageIdForModify) {
		this.languageIdForModify = languageIdForModify;
	}

	public List<ResourceTypeInfoDto> getResourceList() {
		return resourceList;
	}

	public void setResourceList(List<ResourceTypeInfoDto> resourceList) {
		this.resourceList = resourceList;
	}

	public int getResourceTypeId() {
		return resourceTypeId;
	}

	public void setResourceTypeId(int resourceTypeId) {
		this.resourceTypeId = resourceTypeId;
	}

}
